package com.tgu.home_action.controller;

import com.tgu.home_action.pojo.Family;
import com.tgu.home_action.pojo.annotation.ApiJsonObject;
import com.tgu.home_action.pojo.annotation.ApiJsonProperty;
import com.tgu.home_action.pojo.ResponseData;
import com.tgu.home_action.pojo.annotation.MyLog;
import com.tgu.home_action.pojo.exception.IMException;
import com.tgu.home_action.pojo.state.ResponseState;
import com.tgu.home_action.service.FamilyService;
import io.jsonwebtoken.ExpiredJwtException;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.constraints.Pattern;
import java.io.IOException;
import java.util.Map;

@Api(tags = "家属端的用户管理")
@Validated
@RestController
@RequestMapping("/family")
public class       FamilyController {
    @Autowired
    private Logger logger;
    @Autowired
    private FamilyService familyService;

    @MyLog(actionId = 1, role = "family", type = 2)
    @ApiOperation("登录")
    @PostMapping("/login")
    public ResponseData<Family> login(@ApiJsonObject(name = "FamilyLoginCode", value = {
            @ApiJsonProperty(key = "code", description = "从微信获取的code")
    }) @RequestBody Map<String, Object> param) {
        return familyService.login((String) param.get("code"));
    }

    /**
     * 更新微信获取的信息
     *
     * @param param：信息
     * @param familyUser：当前登录的用户
     * @return responseData
     */
    @MyLog(actionId = 3, role = "family", type = 3)
    @ApiOperation("更新获取的微信用户信息")
    @PreAuthorize("hasRole('family')")
    @ApiResponses({
            @ApiResponse(message = "请求成功", code = 200),
            @ApiResponse(message = "请求失败", code = 100)
    })
    @PostMapping("/userinfo")
    public ResponseData<Object> updateUserinfo(@ApiJsonObject(name = "FamilyUserinfo", value = {
            @ApiJsonProperty(key = "encryptedData", description = "加密字符串"),
            @ApiJsonProperty(key = "iv", description = "从微信获取的iv")
    }) @RequestBody Map<String, Object> param, @ApiIgnore @ModelAttribute("familyUser") Family familyUser) {
        String encryptedData = (String) param.get("encryptedData");
        String iv = (String) param.get("iv");
        return familyService.updateUserinfo(encryptedData, iv, familyUser);
    }

    @ApiOperation("更新Token")
    @PostMapping("/refresh")
    public ResponseData<Object> refreshToken(@ApiJsonObject(name = "FamilyRefreshToken",
            value = @ApiJsonProperty(key = "refreshToken", description = "refreshToken")) @RequestBody Map<String, Object> param) {
        try {
            return familyService.refreshToken((String) param.get("refreshToken"));
        } catch (ExpiredJwtException e) {
            logger.warn("token已过期");
            logger.error(e.getMessage());
            return new ResponseData<>(ResponseState.REFRESH_TOKEN_IS_EXPIRED.getMessage(), ResponseState.REFRESH_TOKEN_IS_EXPIRED.getValue());
        } catch (Exception e) {
            System.out.println(e);
            logger.error("发生错误");
            logger.error(e.getMessage());
            return new ResponseData<>(ResponseState.REFRESH_TOKEN_IS_ERROR.getMessage(), ResponseState.REFRESH_TOKEN_IS_ERROR.getValue());
        }
    }

    @ApiOperation("绑定手机号时获取验证码")
    @PreAuthorize("hasRole('family')")
    @GetMapping("/getBindCode")
    public ResponseData<Object> getBindCode(@ApiParam(name = "phone", value = "手机号", required = true)
                                            @Pattern(regexp = "^[1]([3-9])[0-9]{9}$", message = "手机号格式错误") @RequestParam String phone, @ApiIgnore @ModelAttribute("familyUser") Family familyUser) {
        return familyService.getBindCode(phone, familyUser);
    }

    @ApiOperation("修改手机号时获取验证码")
    @PreAuthorize("hasRole('family')")
    @GetMapping("/getUpdateCode")
    public ResponseData<Object> getUpdateCode(@ApiParam(name = "phone", value = "手机号", required = true)
                                              @Pattern(regexp = "^[1]([3-9])[0-9]{9}$", message = "手机号格式错误") @RequestParam String phone, @ApiIgnore @ModelAttribute("familyUser") Family familyUser) {
        return familyService.getUpdateCode(phone, familyUser);
    }


    @MyLog(actionId = 4, role = "family", type = 3)
    @ApiOperation(value = "绑定/修改手机号")
    @PreAuthorize("hasRole('family')")
    @PostMapping("/phone")
    public ResponseData<Object> completeInformation(@ApiJsonObject(name = "FamilyInformation", value = {
            @ApiJsonProperty(key = "phone", description = "手机号"),
            @ApiJsonProperty(key = "code", description = "短信验证码")
    }) @RequestBody Map<String, Object> param, @ApiIgnore @ModelAttribute("familyUser") Family familyUser) {
        String phone = (String) param.get("phone");
        String code = (String) param.get("code");
        return familyService.bindPhone(phone, code, familyUser);
    }

    @ApiOperation("家属上传图片")
    @PreAuthorize("hasRole('family')")
    @PostMapping("/photo")
    public ResponseData<String> uploadPhoto(@RequestParam(required = true, name = "photo") MultipartFile photo, @ApiIgnore @ModelAttribute("familyUser") Family familyUser) {
        try {
            return familyService.uploadPhoto(photo, familyUser);
        } catch (IOException e) {
            logger.error("家属上传图片时获得文件流失败");
            logger.error(e.getMessage());
            return new ResponseData<>(ResponseState.NOT_CAN_GET_FILE_STREAM.getMessage(), ResponseState.NOT_CAN_GET_FILE_STREAM.getValue());
        }
    }

    @MyLog(actionId = 7, type = 3, role = "family")
    @PreAuthorize("hasRole('family')")
    @ApiOperation("更换头像")
    @PutMapping("/avatar")
    public ResponseData<String> updateAvatar(@ApiJsonObject(name = "FamilyAvatarUrl", value = @ApiJsonProperty(key = "avatarUrl", description = "头像链接"))
                                             @RequestBody Map<String, Object> param, @ApiIgnore @ModelAttribute("familyUser") Family familyUser) {
        return familyService.updateAvatar((String) param.get("avatarUrl"), familyUser);
    }

    @ApiOperation("获取个人信息")
    @PreAuthorize("hasRole('family')")
    @GetMapping
    public ResponseData<Family> getFamily(@ApiIgnore @ModelAttribute("familyUser") Family familyUser) {
        return familyService.getFamily(familyUser);
    }

    @ApiOperation("IM获取UserSig")
    @PreAuthorize("hasRole('family')")
    @GetMapping("/im/userSig")
    public ResponseData<String> getUserSig(@ApiIgnore @ModelAttribute("familyUser") Family family) {
        try {
            return familyService.getUserSig(family);
        } catch (IMException e) {
            return new ResponseData<>(e.getMessage(), ResponseState.IM_ERROR.getValue());
        }
    }

    @ApiOperation("修改个人信息")
    @PreAuthorize("hasRole('family')")
    @PutMapping("/info")
    public ResponseData<Object> updateInfo(@RequestBody Family family, @ApiIgnore @ModelAttribute("familyUser") Family familyUser) {
        return familyService.updateInfo(family, familyUser);
    }

    @ApiOperation("通过Id查询")
    @GetMapping("/id")
    public ResponseData<Family> getById(@RequestParam Integer id) {
        return familyService.getById(id);
    }

}
